package com.qianfeng.smartmeeting.service.impl;

import com.qianfeng.smartmeeting.dto.LoginDto;
import com.qianfeng.smartmeeting.dto.RegisterDto;
import com.qianfeng.smartmeeting.entity.User;
import com.qianfeng.smartmeeting.exception.BusinessException;
import com.qianfeng.smartmeeting.service.AuthService;
import com.qianfeng.smartmeeting.service.UserService;
import com.qianfeng.smartmeeting.utils.ResponseResult;
import com.qianfeng.smartmeeting.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private UserService userService;
    
//    @Autowired
//    private PasswordEncoder passwordEncoder;
//
//    @Autowired
//    private JwtTokenUtil jwtTokenUtil;
    
    @Override
    public ResponseResult<LoginVo> login(LoginDto loginDto) {
        User user = userService.getUserByUsername(loginDto.getUsername());
//        if (user == null || !passwordEncoder.matches(loginDto.getPassword(), user.getPassword())) {
//            throw new BusinessException("用户名或密码错误");
//        }
//
//        if (user.getStatus() == 0) {
//            throw new BusinessException("账号已被禁用，请联系管理员");
//        }
        
        // 更新最后登录时间
        user.setLastLoginTime(new Date());
        userService.updateById(user);
        
        // 生成token
//        UserDetails userDetails = new org.springframework.security.core.userdetails.User(
//                user.getUsername(),
//                user.getPassword(),
//                Collections.singleton(new SimpleGrantedAuthority(user.getRole()))
//        );
        //String token = jwtTokenUtil.generateToken(userDetails);
        
        // 返回结果
        LoginVo loginVo = new LoginVo();
        //loginVo.setToken(token);
        loginVo.setUser(user);
        return ResponseResult.success("登录成功", loginVo);
    }
    
    @Override
    public ResponseResult<?> register(RegisterDto registerDto) {
        if (userService.getUserByUsername(registerDto.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }
        
        User user = new User();
        user.setUsername(registerDto.getUsername());
        //user.setPassword(passwordEncoder.encode(registerDto.getPassword()));
        user.setRealName(registerDto.getRealName());
        user.setEmail(registerDto.getEmail());
        user.setPhone(registerDto.getPhone());
        user.setRole("ROLE_USER");
        user.setStatus(1);
        
        userService.save(user);
        return ResponseResult.success("注册成功");
    }
}